package com.robotserver.orders.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.jd.open.api.sdk.DefaultJdClient;
import com.jd.open.api.sdk.JdClient;
import com.jd.open.api.sdk.JdException;
import com.jd.open.api.sdk.domain.kplunion.OrderService.request.query.OrderAgentReq;
import com.jd.open.api.sdk.domain.kplunion.OrderService.request.query.OrderRowReq;
import com.jd.open.api.sdk.domain.kplunion.OrderService.response.query.*;
import com.jd.open.api.sdk.request.kplunion.UnionOpenOrderAgentQueryRequest;
import com.jd.open.api.sdk.request.kplunion.UnionOpenOrderRowQueryRequest;
import com.jd.open.api.sdk.response.kplunion.UnionOpenOrderAgentQueryResponse;
import com.jd.open.api.sdk.response.kplunion.UnionOpenOrderRowQueryResponse;
import com.robotserver.orders.common.DateUtil;
import com.robotserver.orders.common.Math;
import com.robotserver.orders.entity.*;
import com.robotserver.orders.mapper.JdOrdersInfoMapper;
import com.robotserver.orders.mapper.JdOrdersMapper;
import com.robotserver.orders.mapper.JdTokensMapper;
import com.robotserver.orders.mapper.SysSettingMapper;
import com.robotserver.orders.param.JdOrderApiPullDto;
import com.robotserver.orders.service.JdCpsOrderService;
import com.robotserver.orders.service.JdOrderSyncService;
import com.robotserver.orders.service.MiniProSubMsgService;
import com.robotserver.orders.service.OrdersNotifyService;
import com.robotserver.orders.vo.JdOrderTimeVO;
import com.robotserver.orders.vo.biz.JdOrderVO;
import com.robotserver.orders.vo.biz.PageVO;
import com.robotserver.orders.vo.jdcpsorder.JdCpsOrderResp;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Auther: jianghan
 * @Date: 2019/11/8 11:24
 * @Description:
 */
@Service
public class JdOrderSyncServiceImpl implements JdOrderSyncService {

    private static Logger logger = LoggerFactory.getLogger(JdOrderSyncServiceImpl.class);

    private static int pagesize = 20;
    private static int type = 3;            // 按照更新时间来查询

    @Autowired
    private JdOrdersMapper jdOrdersMapper;
    @Autowired
    private RedissonClient redissonClient;
    @Value("${jd.sdk.url}")
    private String jdSdkUrl;
    @Autowired
    private SysSettingMapper sysSettingMapper;
    @Autowired
    private MiniProSubMsgService miniProSubMsgService;
    @Autowired
    private JdTokensMapper jdTokensMapper;
    @Autowired
    private JdCpsOrderService jdCpsOrderService;
    @Autowired
    private JdOrdersInfoMapper jdOrdersInfoMapper;
    @Autowired
    private OrdersNotifyService ordersNotifyService;

    @Async("taskExecutor")
    @Override
    public void threadSyncOrder(List<JdTokens> jdTokens,List<JdOrderTimeVO> jdOrderTimeScope,
                                JdClient client,String lockName) {
            threadLockSyncOrder(jdTokens,jdOrderTimeScope,client,lockName);
    }

    @Override
    public void threadLockSyncOrder(List<JdTokens> jdTokens, List<JdOrderTimeVO> jdOrderTimeScope, JdClient client,String lockName) {

        if (jdTokens.size()>0){
            JdTokens token = null;
            RLock lock = null;
            try {
                lock = redissonClient.getLock(lockName);
                lock.lock();

                token = jdTokens.get(0);
                // 删除对象
                jdTokens.remove(token);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (lock!=null){
                    lock.unlock();
                }
            }

            if (token!=null){
                logger.info(lockName+"::token>"+token.getUnionId()+"::size:"+jdTokens.size());
                syncUnionUnitOrder(jdOrderTimeScope,token,client);
                threadLockSyncOrder(jdTokens,jdOrderTimeScope,client,lockName);
            }
        }
    }

    @Override
    public void syncUnionUnitOrder(List<JdOrderTimeVO> jdOrderTimeScope,JdTokens token,JdClient client) {
        for (JdOrderTimeVO jdOrderTimeVO:jdOrderTimeScope){
            syncTimeUnitOrder(jdOrderTimeVO,token,1,client);
        }
    }

    @Override
    public void syncTimeUnitOrder(JdOrderTimeVO jdOrderTimeVO,JdTokens token, int pageNo,JdClient client) {
        try {

            if (token.getType()==null || token.getType()==1){
                //UnionOpenOrderQueryRequest request = new UnionOpenOrderQueryRequest();
                UnionOpenOrderRowQueryRequest request=new UnionOpenOrderRowQueryRequest();
                //OrderReq orderReq=new OrderReq();
                OrderRowReq orderReq=new OrderRowReq();
                orderReq.setPageIndex(pageNo);
                orderReq.setPageSize(pagesize);
                orderReq.setType(type);
                orderReq.setStartTime(jdOrderTimeVO.getBeginTime());
                orderReq.setEndTime(jdOrderTimeVO.getEndTime());
                orderReq.setKey(token.getAuthKey());
                orderReq.setFields("goodsInfo,categoryInfo"); //筛选出参，多项逗号分隔，目前支持：categoryInfo、goodsInfo
                request.setOrderReq(orderReq);
                //UnionOpenOrderQueryResponse response=client.execute(request);
                UnionOpenOrderRowQueryResponse response=client.execute(request);

                if (response!=null){
                    if (response.getCode() != null && Integer.parseInt(response.getCode())==1002006){
                        miniProSubMsgService.sendAuthInvalid("京东",token.getUnionId(),null);
                    }

                    OrderRowQueryResult queryResult = response.getQueryResult();
                    if(queryResult != null){
                        // 处理订单入库
                        ordersAdd(queryResult.getData());
                        if (queryResult.getHasMore()!=null && queryResult.getHasMore()){
                            pageNo = pageNo+1;
                            syncTimeUnitOrder(jdOrderTimeVO,token,pageNo,client);
                        }else{
                            // 修改心跳
                            if (token.getId()!=null){
                                int now = DateUtil.getNowTime();
                                jdTokensMapper.updateHeartbeat(token.getId(),now);
                            }
                        }
                    }
                }else{
                    // 修改心跳
                    if (token.getId()!=null){
                        int now = DateUtil.getNowTime();
                        jdTokensMapper.updateHeartbeat(token.getId(),now);
                    }
                }
            }else{
                // 京佣计划
                JdCpsOrderResp jdCpsOrderResp = jdCpsOrderService.getCpsOrders(token.getAuthKey(),jdOrderTimeVO,pageNo,null);
                if (jdCpsOrderResp!=null){
                    if (jdCpsOrderResp.getData()!=null &&
                            jdCpsOrderResp.getData().getOrderRespList()!=null && jdCpsOrderResp.getData().getOrderRespList().size()>0){
                        // 处理订单入库
                        jdCpsOrderService.orderAdd(jdCpsOrderResp.getData());
                        pageNo = pageNo+1;
                        syncTimeUnitOrder(jdOrderTimeVO,token,pageNo,client);
                    }else{
                        // 修改心跳
                        if (token.getId()!=null){
                            int now = DateUtil.getNowTime();
                            jdTokensMapper.updateHeartbeat(token.getId(),now);
                        }
                    }
                }else{
                    // 修改心跳
                    if (token.getId()!=null){
                        int now = DateUtil.getNowTime();
                        jdTokensMapper.updateHeartbeat(token.getId(),now);
                    }
                }
            }
        } catch (Exception e) {
            logger.error("jd sync order err:",e);
        }
    }

    @Override
    public void ordersAdd(OrderRowResp[] OrderRowResps) {
        int now = DateUtil.getNowTime();
        if (OrderRowResps==null || OrderRowResps.length==0){
            logger.info("jd order is null.");
            return ;
        }
        for (OrderRowResp skuInfo:OrderRowResps){

            if(skuInfo.getPrice() == null || skuInfo.getPrice().doubleValue() <= 0){
                //价格等于0，不处理
                continue;
            }

           int bizStatus = bizStatus(skuInfo.getValidCode());
           if (bizStatus==4){
               // 无效订单不处理
               // continue;
           }
           // 根据订单号，商品id查询订单是否存在
           JdOrders jdOrders = jdOrdersMapper.getBySkuIdAndOrderId(skuInfo.getSkuId(),skuInfo.getOrderId());
           if (jdOrders!=null){
                // 修改
//                if ((skuInfo.getValidCode().intValue()!=jdOrders.getSkuValidCode().intValue()) ||
//                        (jdOrders.getBizStatus()!=null && bizStatus!=jdOrders.getBizStatus().intValue())){      // 状态不同就修改

                //modify by liuqi  on 2021-07-13 根据最后更新时间来进行判断，如果更新时间不一样，就修改
                if(DateUtil.getStrTime(skuInfo.getModifyTime()) != jdOrders.getModifyTime().intValue()){

                    if(skuInfo.getSkuReturnNum() !=null && skuInfo.getSkuReturnNum().intValue()>0){
                        bizStatus = 2;      // 订单失效
                    }

                    //判断实际佣金是否与数据库佣金不一样，如果不一样，就退款
                    if(Math.currencyFormatToF(skuInfo.getActualFee()) < jdOrders.getActualFee()){
                        bizStatus = 2;      // 订单失效-维权
                    }

                    jdOrders.setFinishTime(DateUtil.getStrTime(skuInfo.getFinishTime()));
                    jdOrders.setOrderEmt(skuInfo.getOrderEmt());
                    jdOrders.setOrderId(skuInfo.getOrderId());
                    jdOrders.setOrderTime(DateUtil.getStrTime(skuInfo.getOrderTime()));
                    jdOrders.setParentId(skuInfo.getParentId());
                    jdOrders.setPayMonth(skuInfo.getPayMonth());
                    jdOrders.setPlus(skuInfo.getPlus());
                    jdOrders.setPopId(skuInfo.getPopId());
                    jdOrders.setUnionId(skuInfo.getUnionId());
                    jdOrders.setExt1(skuInfo.getExt1());
                    jdOrders.setValidCode(skuInfo.getValidCode());
                    jdOrders.setActualCosPrice(Math.currencyFormatToF(skuInfo.getActualCosPrice()));
                    jdOrders.setActualFee(Math.currencyFormatToF(skuInfo.getActualFee()));
                    jdOrders.setCommissionRate(skuInfo.getCommissionRate());
                    jdOrders.setEstimateCosPrice(Math.currencyFormatToF(skuInfo.getEstimateCosPrice()));
                    jdOrders.setEstimateFee(Math.currencyFormatToF(skuInfo.getEstimateFee()));
                    jdOrders.setFinalRate(skuInfo.getFinalRate());
                    jdOrders.setCid1(skuInfo.getCid1());
                    jdOrders.setFrozenSkuNum(skuInfo.getSkuFrozenNum());
                    jdOrders.setPid(skuInfo.getPid());
                    jdOrders.setPositionId(skuInfo.getPositionId());
                    jdOrders.setPrice(Math.currencyFormatToF(skuInfo.getPrice()));
                    jdOrders.setCid2(skuInfo.getCid2());
                    jdOrders.setCid3(skuInfo.getCid3());
                    jdOrders.setSiteId(skuInfo.getSiteId());
                    jdOrders.setSkuId(skuInfo.getSkuId());
                    jdOrders.setSkuName(skuInfo.getSkuName());
                    jdOrders.setSkuNum(skuInfo.getSkuNum());
                    jdOrders.setSkuReturnNum(skuInfo.getSkuReturnNum());
                    jdOrders.setSubSideRate(skuInfo.getSubSideRate());
                    jdOrders.setSubsidyRate(skuInfo.getSubsidyRate());
                    jdOrders.setUnionAlias(skuInfo.getUnionAlias());
                    jdOrders.setUnionTag(skuInfo.getUnionTag());
                    //新版接口没有返回这个渠道组字段
                    //jdOrders.setUnionTrafficGroup(skuInfo.getUnionTrafficGroup());
                    jdOrders.setSkuValidCode(skuInfo.getValidCode());
                    jdOrders.setSubUnionId(skuInfo.getSubUnionId());
                    jdOrders.setTraceType(skuInfo.getTraceType());
                    jdOrders.setSkuPayMonth(DateUtil.getStrTime(skuInfo.getPayMonth(),"yyyyMMdd"));
                    jdOrders.setSkuPopId(skuInfo.getPopId());
                    jdOrders.setSkuExt1(skuInfo.getExt1());
                    jdOrders.setCpActId(skuInfo.getCpActId());
                    jdOrders.setUnionRole(skuInfo.getUnionRole());
                    jdOrders.setGiftCouponKey(skuInfo.getGiftCouponKey());
                    jdOrders.setGiftCouponOcsAmount(Math.currencyFormatToF(skuInfo.getGiftCouponOcsAmount()));
                    jdOrders.setBizStatus(bizStatus);

                    //modify by liuqi on 2021-07-13 业务状态最后还得根据退货数量来判断，如果有退货数量，则状态变成维权订单
                    if(skuInfo.getSkuReturnNum() != null && skuInfo.getSkuReturnNum().intValue() > 0){
                        jdOrders.setBizStatus(2);
                    }

                    jdOrders.setImgUrl(skuInfo.getGoodsInfo()!=null?skuInfo.getGoodsInfo().getImageUrl():null);
                    jdOrders.setModifyTime(DateUtil.getStrTime(skuInfo.getModifyTime()));
                    jdOrders.setBalanceExt(skuInfo.getBalanceExt());
                    jdOrders.setProPriceAmount(Math.currencyFormatToF(skuInfo.getProPriceAmount()));
                    jdOrders.setOwner(skuInfo.getGoodsInfo()!=null?skuInfo.getGoodsInfo().getOwner():null);
                    jdOrders.setMainSkuId(skuInfo.getGoodsInfo()!=null?skuInfo.getGoodsInfo().getMainSkuId():null);
                    jdOrders.setProductId(skuInfo.getGoodsInfo()!=null?skuInfo.getGoodsInfo().getProductId():null);
                    jdOrders.setShopName(skuInfo.getGoodsInfo()!=null?skuInfo.getGoodsInfo().getShopName():null);
                    jdOrders.setShopId(skuInfo.getGoodsInfo()!=null?skuInfo.getGoodsInfo().getShopId():null);
                    jdOrders.setCid1Name(skuInfo.getCategoryInfo()!=null?skuInfo.getCategoryInfo().getCid1Name():null);
                    jdOrders.setCid2Name(skuInfo.getCategoryInfo()!=null?skuInfo.getCategoryInfo().getCid2Name():null);
                    jdOrders.setCid3Name(skuInfo.getCategoryInfo()!=null?skuInfo.getCategoryInfo().getCid3Name():null);
                    jdOrders.setExpressStatus(skuInfo.getExpressStatus());
                    jdOrders.setFailReason(getPunishInfo(skuInfo.getValidCode()));
                    jdOrders.setRid("");
                    jdOrders.setItemId(skuInfo.getItemId());
                    jdOrders.setCallerItemId(skuInfo.getCallerItemId());
                    jdOrders.setUpdateTime(now);
                    jdOrdersMapper.update(jdOrders);
                }
           }else {

               if(skuInfo.getSkuReturnNum() !=null && skuInfo.getSkuReturnNum().intValue()>0){
                   bizStatus = 2;      // 订单失效
               }

               if (bizStatus==5){   // 无效-拆单 不处理
                   // continue;
               }
               // 添加京东订单
               JdOrders newJdOrder = new JdOrders();
               newJdOrder.setId(IdWorker.getId());
               newJdOrder.setFinishTime(DateUtil.getStrTime(skuInfo.getFinishTime()));
               newJdOrder.setOrderEmt(skuInfo.getOrderEmt());
               newJdOrder.setOrderId(skuInfo.getOrderId());
               newJdOrder.setOrderTime(DateUtil.getStrTime(skuInfo.getOrderTime()));
               newJdOrder.setParentId(skuInfo.getParentId());
               newJdOrder.setPayMonth(skuInfo.getPayMonth());
               newJdOrder.setPlus(skuInfo.getPlus());
               newJdOrder.setPopId(skuInfo.getPopId());
               newJdOrder.setUnionId(skuInfo.getUnionId());
               newJdOrder.setExt1(skuInfo.getExt1());
               newJdOrder.setValidCode(skuInfo.getValidCode());
               newJdOrder.setActualCosPrice(Math.currencyFormatToF(skuInfo.getActualCosPrice()));
               newJdOrder.setActualFee(Math.currencyFormatToF(skuInfo.getActualFee()));
               newJdOrder.setCommissionRate(skuInfo.getCommissionRate());
               newJdOrder.setEstimateCosPrice(Math.currencyFormatToF(skuInfo.getEstimateCosPrice()));
               newJdOrder.setEstimateFee(Math.currencyFormatToF(skuInfo.getEstimateFee()));
               newJdOrder.setFinalRate(skuInfo.getFinalRate());
               newJdOrder.setCid1(skuInfo.getCid1());
               newJdOrder.setFrozenSkuNum(skuInfo.getSkuFrozenNum().intValue());
               newJdOrder.setPid(skuInfo.getPid());
               newJdOrder.setPositionId(skuInfo.getPositionId());
               newJdOrder.setPrice(Math.currencyFormatToF(skuInfo.getPrice()));
               newJdOrder.setCid2(skuInfo.getCid2());
               newJdOrder.setCid3(skuInfo.getCid3());
               newJdOrder.setSiteId(skuInfo.getSiteId());
               newJdOrder.setSkuId(skuInfo.getSkuId());
               newJdOrder.setSkuName(skuInfo.getSkuName());
               newJdOrder.setSkuNum(skuInfo.getSkuNum().intValue());
               newJdOrder.setSkuReturnNum(skuInfo.getSkuReturnNum().intValue());
               newJdOrder.setSubSideRate(skuInfo.getSubSideRate());
               newJdOrder.setSubsidyRate(skuInfo.getSubsidyRate());
               newJdOrder.setUnionAlias(skuInfo.getUnionAlias());
               newJdOrder.setUnionTag(skuInfo.getUnionTag());
               //新版接口没有返回这个渠道组字段
               //newJdOrder.setUnionTrafficGroup(skuInfo.getUnionTrafficGroup());
               newJdOrder.setSkuValidCode(skuInfo.getValidCode());
               newJdOrder.setSubUnionId(skuInfo.getSubUnionId());
               newJdOrder.setTraceType(skuInfo.getTraceType());
               newJdOrder.setSkuPayMonth(DateUtil.getStrTime(skuInfo.getPayMonth(),"yyyyMMdd"));
               newJdOrder.setSkuPopId(skuInfo.getPopId());
               newJdOrder.setSkuExt1(skuInfo.getExt1());
               newJdOrder.setCpActId(skuInfo.getCpActId());
               newJdOrder.setUnionRole(skuInfo.getUnionRole());
               newJdOrder.setGiftCouponKey(skuInfo.getGiftCouponKey());
               newJdOrder.setGiftCouponOcsAmount(Math.currencyFormatToF(skuInfo.getGiftCouponOcsAmount()));
               newJdOrder.setBizStatus(bizStatus);
               newJdOrder.setImgUrl(skuInfo.getGoodsInfo()!=null?skuInfo.getGoodsInfo().getImageUrl():null);
               newJdOrder.setModifyTime(DateUtil.getStrTime(skuInfo.getModifyTime()));
               newJdOrder.setBalanceExt(skuInfo.getBalanceExt());
               newJdOrder.setProPriceAmount(Math.currencyFormatToF(skuInfo.getProPriceAmount()));
               newJdOrder.setOwner(skuInfo.getGoodsInfo()!=null?skuInfo.getGoodsInfo().getOwner():null);
               newJdOrder.setMainSkuId(skuInfo.getGoodsInfo()!=null?skuInfo.getGoodsInfo().getMainSkuId():null);
               newJdOrder.setProductId(skuInfo.getGoodsInfo()!=null?skuInfo.getGoodsInfo().getProductId():null);
               newJdOrder.setShopName(skuInfo.getGoodsInfo()!=null?skuInfo.getGoodsInfo().getShopName():null);
               newJdOrder.setShopId(skuInfo.getGoodsInfo()!=null?skuInfo.getGoodsInfo().getShopId():null);
               newJdOrder.setCid1Name(skuInfo.getCategoryInfo()!=null?skuInfo.getCategoryInfo().getCid1Name():null);
               newJdOrder.setCid2Name(skuInfo.getCategoryInfo()!=null?skuInfo.getCategoryInfo().getCid2Name():null);
               newJdOrder.setCid3Name(skuInfo.getCategoryInfo()!=null?skuInfo.getCategoryInfo().getCid3Name():null);
               newJdOrder.setExpressStatus(skuInfo.getExpressStatus());
               newJdOrder.setFailReason(getPunishInfo(skuInfo.getValidCode()));
               newJdOrder.setRid("");
               newJdOrder.setItemId(skuInfo.getItemId());
               newJdOrder.setCallerItemId(skuInfo.getCallerItemId());
               newJdOrder.setUpdateTime(now);
               newJdOrder.setCreateTime(now);

               //保存订单
               jdOrdersMapper.add(newJdOrder);
           }
        }
    }

    private int bizStatus(int validCode){
        // 16 付款 17 已完成 3 13 失效 2 无效-拆单
        switch (validCode){
            case 16:
                return 0;
            case 24:
                return 0;
            case 17:
                return 1;
            case 2:
                return 2;
            case 3:
                return 2;
            case 4:
                return 2;
            case 5:
                return 2;
            case 6:
                return 2;
            case 7:
                return 2;
            case 8:
                return 2;
            case 9:
                return 2;
            case 11:
                return 2;
            case 14:
                return 2;
            case 13:
                return 8;
            case 25:
                return 8;
            case 26:
                return 8;
            case 27:
                return 8;
            case 28:
                return 8;
        }
        return 4;
    }

    private String getPunishInfo(int validCode){
        // 16 付款 17 已完成 3 13 失效 2 无效-拆单
        switch (validCode){
            case 13:
                return "违规订单-其他";
            case 25:
                return "违规订单-流量劫持";
            case 26:
                return "违规订单-流量异常";
            case 27:
                return "违规订单-违反京东平台规则";
            case 28:
                return "违规订单-多笔交易异常";
        }
        return "";
    }

    @Async("taskExecutor")
    @Override
    public void threadSyncOrder_consumer(JdTokens jdTokens,List<JdOrderTimeVO> jdOrderTimeScope, JdClient client) {
        syncUnionUnitOrder(jdOrderTimeScope,jdTokens,client);
    }

    @Override
    public void threadSyncOrder_byAppKey(List<JdOrderTimeVO> jdOrderTimeVOList, JdClient client, Integer downType){
        for (JdOrderTimeVO jdOrderTimeVO:jdOrderTimeVOList){
            syncTimeOrder_byAppKey(jdOrderTimeVO,1,client, downType);
        }
    }

    public void syncTimeOrder_byAppKey(JdOrderTimeVO jdOrderTimeVO, int pageNo,JdClient client, Integer downType) {
        try {
            //UnionOpenOrderQueryRequest request = new UnionOpenOrderQueryRequest();
            UnionOpenOrderAgentQueryRequest request = new UnionOpenOrderAgentQueryRequest();
            //OrderReq orderReq=new OrderReq();
            OrderAgentReq orderReq = new OrderAgentReq();
            orderReq.setPageIndex(pageNo);
            orderReq.setPageSize(pagesize);
            orderReq.setStartTime(jdOrderTimeVO.getBeginTime());
            orderReq.setEndTime(jdOrderTimeVO.getEndTime());
            if(downType != null){
                orderReq.setType(downType);
            }else{
                orderReq.setType(type); //订单更新时间
            }

            orderReq.setFields("goodsInfo,categoryInfo"); //筛选出参，多项逗号分隔，目前支持：categoryInfo、goodsInfo
            request.setOrderReq(orderReq);
            //UnionOpenOrderQueryResponse response=client.execute(request);
            UnionOpenOrderAgentQueryResponse response = client.execute(request);
            if (response!=null){
                OrderAgentQueryResult orderAgentQueryResult = response.getQueryResult();
                if(orderAgentQueryResult != null){
                    //处理京东订单
                    ordersAdd_byAppKey(orderAgentQueryResult.getData());
                    //额外某个联盟订单进行数据判断
                    //ordersInfoAdd_byAppKey(orderAgentQueryResult.getData(), orderReq);
                    if (orderAgentQueryResult.getHasMore()!=null && orderAgentQueryResult.getHasMore()){
                        pageNo = pageNo+1;
                        //递归请求下一页的数据
                        syncTimeOrder_byAppKey(jdOrderTimeVO, pageNo, client, downType);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("-----jd sync order err:--------",e);
        }
    }

    public void ordersAdd_byAppKey(OrderAgentResp[] orderAgentResps) {
        int now = DateUtil.getNowTime();
        if (orderAgentResps==null || orderAgentResps.length==0){
            logger.info("-----jd order is null.-------");
            return ;
        }

        for (OrderAgentResp skuInfo : orderAgentResps){


            //自定义参数不为空，且以cps_开头，这种订单为推老板订单，不入库
            String subUnionId = skuInfo.getSubUnionId();

            //是否开启自定义参数为空过滤（0-不过滤;1-过滤）
            String jd_order_sub_union_id = sysSettingMapper.getByKey("jd_order_sub_union_id");
            if(StringUtils.isNotBlank(jd_order_sub_union_id) && "1".equals(jd_order_sub_union_id)){
                //速推订单的自定义参数为空
                if(StringUtils.isBlank(subUnionId)){
                    continue;
                }
            }

            if(StringUtils.isNotBlank(subUnionId) && subUnionId.startsWith("cps_")) {
                logger.info("----JD cps orders : id={}, skuid: {}, orderid: {}, validCode={}, price={}, skuFrozenNum={}, skuReturnNum={}, actualFee={}, subUnionId={}",
                        new Object[]{skuInfo.getId(), skuInfo.getSkuId(), skuInfo.getOrderId(), skuInfo.getValidCode(), skuInfo.getPrice(), skuInfo.getSkuFrozenNum(), skuInfo.getSkuReturnNum(), skuInfo.getActualFee(),subUnionId});
                continue;
            }

            logger.info("----JD orders : id={}, skuid: {}, orderid: {}, validCode={}, price={}, skuFrozenNum={}, skuReturnNum={}, actualFee={}",
                    new Object[]{skuInfo.getId(), skuInfo.getSkuId(), skuInfo.getOrderId(), skuInfo.getValidCode(), skuInfo.getPrice(), skuInfo.getSkuFrozenNum(), skuInfo.getSkuReturnNum(), skuInfo.getActualFee()});

            if(skuInfo.getPrice() == null || skuInfo.getPrice().doubleValue() <= 0){
                //价格等于0，不处理
                continue;
            }

            //update by:20221123 待付款不处理  validCode = 15 待付款
            if(skuInfo.getValidCode() != null  && skuInfo.getValidCode().intValue() == 15){
                //validCode = 15 待付款，不处理
                continue;
            }

            //订单状态
            int bizStatus = bizStatus(skuInfo.getValidCode());

            // 根据订单号，商品id查询订单是否存在
            JdOrders jdOrders = jdOrdersMapper.getByDataId(skuInfo.getId());
            //直接添加。必须要考虑拆单的情况
            if(jdOrders == null){
                if(skuInfo.getSkuReturnNum() != null && skuInfo.getSkuReturnNum().intValue() > 0){
                    //bizStatus = 2;      // 订单失效
                }

                if (bizStatus==4){
                    // 无效订单不处理
                    // continue;
                }

                if (bizStatus==5){   // 无效-拆单 不处理
                    // continue;
                }

                // 添加京东订单
                JdOrders newJdOrder = new JdOrders();
                newJdOrder.setId(IdWorker.getId());
                newJdOrder.setFinishTime(DateUtil.getStrTime(skuInfo.getFinishTime()));
                newJdOrder.setOrderEmt(skuInfo.getOrderEmt());
                newJdOrder.setOrderId(skuInfo.getOrderId());
                newJdOrder.setDataId(skuInfo.getId());
                newJdOrder.setOrderIdOld(skuInfo.getOrderId());
                newJdOrder.setOrderTime(DateUtil.getStrTime(skuInfo.getOrderTime()));
                newJdOrder.setParentId(skuInfo.getParentId());
                newJdOrder.setPayMonth(skuInfo.getPayMonth());
                newJdOrder.setPlus(skuInfo.getPlus());
                newJdOrder.setPopId(skuInfo.getPopId());
                newJdOrder.setUnionId(skuInfo.getUnionId());
                newJdOrder.setExt1(skuInfo.getExt1());
                newJdOrder.setValidCode(skuInfo.getValidCode());
                newJdOrder.setActualCosPrice(Math.currencyFormatToF(skuInfo.getActualCosPrice()));
                newJdOrder.setActualFee(Math.currencyFormatToF(skuInfo.getActualFee()));
                newJdOrder.setCommissionRate(skuInfo.getCommissionRate());
                newJdOrder.setEstimateCosPrice(Math.currencyFormatToF(skuInfo.getEstimateCosPrice()));
                newJdOrder.setEstimateFee(Math.currencyFormatToF(skuInfo.getEstimateFee()));
                newJdOrder.setFinalRate(skuInfo.getFinalRate());
                newJdOrder.setCid1(skuInfo.getCid1());
                newJdOrder.setFrozenSkuNum(skuInfo.getSkuFrozenNum().intValue());
                newJdOrder.setPid(skuInfo.getPid());
                newJdOrder.setPositionId(skuInfo.getPositionId());
                newJdOrder.setPrice(Math.currencyFormatToF(skuInfo.getPrice()));
                newJdOrder.setCid2(skuInfo.getCid2());
                newJdOrder.setCid3(skuInfo.getCid3());
                newJdOrder.setSiteId(skuInfo.getSiteId());
                newJdOrder.setSkuId(skuInfo.getSkuId());
                newJdOrder.setSkuName(skuInfo.getSkuName());
                newJdOrder.setSkuNum(skuInfo.getSkuNum().intValue());
                newJdOrder.setSkuReturnNum(skuInfo.getSkuReturnNum().intValue());
                newJdOrder.setSubSideRate(skuInfo.getSubSideRate());
                newJdOrder.setSubsidyRate(skuInfo.getSubsidyRate());
                newJdOrder.setUnionAlias(skuInfo.getUnionAlias());
                newJdOrder.setUnionTag(skuInfo.getUnionTag());
                //新版接口没有返回这个渠道组字段
                //newJdOrder.setUnionTrafficGroup(skuInfo.getUnionTrafficGroup());
                newJdOrder.setSkuValidCode(skuInfo.getValidCode());
                newJdOrder.setSubUnionId(skuInfo.getSubUnionId());
                newJdOrder.setTraceType(skuInfo.getTraceType());
                newJdOrder.setSkuPayMonth(DateUtil.getStrTime(skuInfo.getPayMonth(),"yyyyMMdd"));
                newJdOrder.setSkuPopId(skuInfo.getPopId());
                newJdOrder.setSkuExt1(skuInfo.getExt1());
                newJdOrder.setCpActId(skuInfo.getCpActId());
                newJdOrder.setUnionRole(skuInfo.getUnionRole());
                newJdOrder.setGiftCouponKey(skuInfo.getGiftCouponKey());
                newJdOrder.setGiftCouponOcsAmount(Math.currencyFormatToF(skuInfo.getGiftCouponOcsAmount()));
                newJdOrder.setBizStatus(bizStatus);
                newJdOrder.setImgUrl(skuInfo.getGoodsInfo()!=null?skuInfo.getGoodsInfo().getImageUrl():null);
                newJdOrder.setModifyTime(DateUtil.getStrTime(skuInfo.getModifyTime()));
                newJdOrder.setBalanceExt(skuInfo.getBalanceExt());
                newJdOrder.setProPriceAmount(Math.currencyFormatToF(skuInfo.getProPriceAmount()));
                newJdOrder.setOwner(skuInfo.getGoodsInfo()!=null?skuInfo.getGoodsInfo().getOwner():null);
                newJdOrder.setMainSkuId(skuInfo.getGoodsInfo()!=null?skuInfo.getGoodsInfo().getMainSkuId():null);
                newJdOrder.setProductId(skuInfo.getGoodsInfo()!=null?skuInfo.getGoodsInfo().getProductId():null);
                newJdOrder.setShopName(skuInfo.getGoodsInfo()!=null?skuInfo.getGoodsInfo().getShopName():null);
                newJdOrder.setShopId(skuInfo.getGoodsInfo()!=null?skuInfo.getGoodsInfo().getShopId():null);
                newJdOrder.setCid1Name(skuInfo.getCategoryInfo()!=null?skuInfo.getCategoryInfo().getCid1Name():null);
                newJdOrder.setCid2Name(skuInfo.getCategoryInfo()!=null?skuInfo.getCategoryInfo().getCid2Name():null);
                newJdOrder.setCid3Name(skuInfo.getCategoryInfo()!=null?skuInfo.getCategoryInfo().getCid3Name():null);
                newJdOrder.setExpressStatus(skuInfo.getExpressStatus());
                newJdOrder.setFailReason(getPunishInfo(skuInfo.getValidCode()));
                newJdOrder.setRid(skuInfo.getRid() != null ? String.valueOf(skuInfo.getRid()) : null);
                newJdOrder.setItemId(skuInfo.getItemId());
                newJdOrder.setCallerItemId(skuInfo.getCallerItemId());
                newJdOrder.setUpdateTime(now);
                newJdOrder.setCreateTime(now);

                //保存订单
                jdOrdersMapper.add(newJdOrder);
            }else{ //如果订单存在，还需要判断是否是拆单订单，因为拆单订单的orderId和skuId不唯一
                if(jdOrders.getDataId() == null || jdOrders.getDataId().equals(skuInfo.getId())){//订单的dataId等于null为旧的订单或者是dataid相同的同一个订单，则直接修改
                    //没有售后中，才根据退货数量和佣金来判断是否失效
                    if(skuInfo.getSkuFrozenNum() == null || skuInfo.getSkuFrozenNum().intValue() == 0){
                        //判断是否有退货
                        if(skuInfo.getSkuReturnNum() !=null && skuInfo.getSkuReturnNum().intValue()>0){
                            //bizStatus = 2;      // 订单失效-维权
                        }

                        //判断实际佣金是否与数据库佣金不一样，如果不一样，就退款
                        if(Math.currencyFormatToF(skuInfo.getActualFee()) < jdOrders.getActualFee()){
                            //bizStatus = 2;      // 订单失效-维权
                        }
                    }

                    jdOrders.setFinishTime(DateUtil.getStrTime(skuInfo.getFinishTime()));
                    jdOrders.setOrderEmt(skuInfo.getOrderEmt());
                    jdOrders.setOrderId(skuInfo.getOrderId());
                    jdOrders.setDataId(skuInfo.getId());
                    jdOrders.setOrderIdOld(skuInfo.getOrderId());
                    jdOrders.setOrderTime(DateUtil.getStrTime(skuInfo.getOrderTime()));
                    jdOrders.setParentId(skuInfo.getParentId());
                    jdOrders.setPayMonth(skuInfo.getPayMonth());
                    jdOrders.setPlus(skuInfo.getPlus());
                    jdOrders.setPopId(skuInfo.getPopId());
                    jdOrders.setUnionId(skuInfo.getUnionId());
                    jdOrders.setExt1(skuInfo.getExt1());
                    jdOrders.setValidCode(skuInfo.getValidCode());
                    jdOrders.setActualCosPrice(Math.currencyFormatToF(skuInfo.getActualCosPrice()));
                    jdOrders.setActualFee(Math.currencyFormatToF(skuInfo.getActualFee()));
                    jdOrders.setCommissionRate(skuInfo.getCommissionRate());
                    jdOrders.setEstimateCosPrice(Math.currencyFormatToF(skuInfo.getEstimateCosPrice()));
                    jdOrders.setEstimateFee(Math.currencyFormatToF(skuInfo.getEstimateFee()));
                    jdOrders.setFinalRate(skuInfo.getFinalRate());
                    jdOrders.setCid1(skuInfo.getCid1());
                    jdOrders.setFrozenSkuNum(skuInfo.getSkuFrozenNum());
                    jdOrders.setPid(skuInfo.getPid());
                    jdOrders.setPositionId(skuInfo.getPositionId());
                    jdOrders.setPrice(Math.currencyFormatToF(skuInfo.getPrice()));
                    jdOrders.setCid2(skuInfo.getCid2());
                    jdOrders.setCid3(skuInfo.getCid3());
                    jdOrders.setSiteId(skuInfo.getSiteId());
                    jdOrders.setSkuId(skuInfo.getSkuId());
                    jdOrders.setSkuName(skuInfo.getSkuName());
                    jdOrders.setSkuNum(skuInfo.getSkuNum());
                    jdOrders.setSkuReturnNum(skuInfo.getSkuReturnNum());
                    jdOrders.setSubSideRate(skuInfo.getSubSideRate());
                    jdOrders.setSubsidyRate(skuInfo.getSubsidyRate());
                    jdOrders.setUnionAlias(skuInfo.getUnionAlias());
                    jdOrders.setUnionTag(skuInfo.getUnionTag());
                    //新版接口没有返回这个渠道组字段
                    //jdOrders.setUnionTrafficGroup(skuInfo.getUnionTrafficGroup());
                    jdOrders.setSkuValidCode(skuInfo.getValidCode());
                    jdOrders.setSubUnionId(skuInfo.getSubUnionId());
                    jdOrders.setTraceType(skuInfo.getTraceType());
                    jdOrders.setSkuPayMonth(DateUtil.getStrTime(skuInfo.getPayMonth(),"yyyyMMdd"));
                    jdOrders.setSkuPopId(skuInfo.getPopId());
                    jdOrders.setSkuExt1(skuInfo.getExt1());
                    jdOrders.setCpActId(skuInfo.getCpActId());
                    jdOrders.setUnionRole(skuInfo.getUnionRole());
                    jdOrders.setGiftCouponKey(skuInfo.getGiftCouponKey());
                    jdOrders.setGiftCouponOcsAmount(Math.currencyFormatToF(skuInfo.getGiftCouponOcsAmount()));
                    jdOrders.setBizStatus(bizStatus);
                    jdOrders.setImgUrl(skuInfo.getGoodsInfo()!=null?skuInfo.getGoodsInfo().getImageUrl():null);
                    jdOrders.setModifyTime(DateUtil.getStrTime(skuInfo.getModifyTime()));
                    jdOrders.setBalanceExt(skuInfo.getBalanceExt());
                    jdOrders.setProPriceAmount(Math.currencyFormatToF(skuInfo.getProPriceAmount()));
                    jdOrders.setOwner(skuInfo.getGoodsInfo()!=null?skuInfo.getGoodsInfo().getOwner():null);
                    jdOrders.setMainSkuId(skuInfo.getGoodsInfo()!=null?skuInfo.getGoodsInfo().getMainSkuId():null);
                    jdOrders.setProductId(skuInfo.getGoodsInfo()!=null?skuInfo.getGoodsInfo().getProductId():null);
                    jdOrders.setShopName(skuInfo.getGoodsInfo()!=null?skuInfo.getGoodsInfo().getShopName():null);
                    jdOrders.setShopId(skuInfo.getGoodsInfo()!=null?skuInfo.getGoodsInfo().getShopId():null);
                    jdOrders.setCid1Name(skuInfo.getCategoryInfo()!=null?skuInfo.getCategoryInfo().getCid1Name():null);
                    jdOrders.setCid2Name(skuInfo.getCategoryInfo()!=null?skuInfo.getCategoryInfo().getCid2Name():null);
                    jdOrders.setCid3Name(skuInfo.getCategoryInfo()!=null?skuInfo.getCategoryInfo().getCid3Name():null);
                    jdOrders.setExpressStatus(skuInfo.getExpressStatus());
                    jdOrders.setFailReason(getPunishInfo(skuInfo.getValidCode()));
                    jdOrders.setRid(skuInfo.getRid() != null ? String.valueOf(skuInfo.getRid()) : null);
                    jdOrders.setItemId(skuInfo.getItemId());
                    jdOrders.setCallerItemId(skuInfo.getCallerItemId());

                    jdOrders.setUpdateTime(now);
                    jdOrdersMapper.update(jdOrders);
                }else{//如果查询到的订单dataId有值，且跟skuInfo的id不一样，则需要把dataId当成orderId再去查询一次
                    //没有售后中，才根据退货数量和佣金来判断是否失效
                    if(skuInfo.getSkuFrozenNum() == null || skuInfo.getSkuFrozenNum().intValue() == 0){
                        //判断是否有退货
                        if(skuInfo.getSkuReturnNum() !=null && skuInfo.getSkuReturnNum().intValue()>0){
                            //bizStatus = 2;      // 订单失效-维权
                        }

                        //判断实际佣金是否与数据库佣金不一样，如果不一样，就退款
                        if(Math.currencyFormatToF(skuInfo.getActualFee()) < jdOrders.getActualFee()){
                            //bizStatus = 2;      // 订单失效-维权
                        }
                    }
                    jdOrders.setFinishTime(DateUtil.getStrTime(skuInfo.getFinishTime()));
                    jdOrders.setOrderEmt(skuInfo.getOrderEmt());
                    jdOrders.setOrderTime(DateUtil.getStrTime(skuInfo.getOrderTime()));
                    jdOrders.setParentId(skuInfo.getParentId());
                    jdOrders.setPayMonth(skuInfo.getPayMonth());
                    jdOrders.setPlus(skuInfo.getPlus());
                    jdOrders.setPopId(skuInfo.getPopId());
                    jdOrders.setUnionId(skuInfo.getUnionId());
                    jdOrders.setExt1(skuInfo.getExt1());
                    jdOrders.setValidCode(skuInfo.getValidCode());
                    jdOrders.setActualCosPrice(Math.currencyFormatToF(skuInfo.getActualCosPrice()));
                    jdOrders.setActualFee(Math.currencyFormatToF(skuInfo.getActualFee()));
                    jdOrders.setCommissionRate(skuInfo.getCommissionRate());
                    jdOrders.setEstimateCosPrice(Math.currencyFormatToF(skuInfo.getEstimateCosPrice()));
                    jdOrders.setEstimateFee(Math.currencyFormatToF(skuInfo.getEstimateFee()));
                    jdOrders.setFinalRate(skuInfo.getFinalRate());
                    jdOrders.setCid1(skuInfo.getCid1());
                    jdOrders.setFrozenSkuNum(skuInfo.getSkuFrozenNum());
                    jdOrders.setPid(skuInfo.getPid());
                    jdOrders.setPositionId(skuInfo.getPositionId());
                    jdOrders.setPrice(Math.currencyFormatToF(skuInfo.getPrice()));
                    jdOrders.setCid2(skuInfo.getCid2());
                    jdOrders.setCid3(skuInfo.getCid3());
                    jdOrders.setSiteId(skuInfo.getSiteId());
                    jdOrders.setSkuId(skuInfo.getSkuId());
                    jdOrders.setSkuName(skuInfo.getSkuName());
                    jdOrders.setSkuNum(skuInfo.getSkuNum());
                    jdOrders.setSkuReturnNum(skuInfo.getSkuReturnNum());
                    jdOrders.setSubSideRate(skuInfo.getSubSideRate());
                    jdOrders.setSubsidyRate(skuInfo.getSubsidyRate());
                    jdOrders.setUnionAlias(skuInfo.getUnionAlias());
                    jdOrders.setUnionTag(skuInfo.getUnionTag());
                    //新版接口没有返回这个渠道组字段
                    //jdOrders.setUnionTrafficGroup(skuInfo.getUnionTrafficGroup());
                    jdOrders.setSkuValidCode(skuInfo.getValidCode());
                    jdOrders.setSubUnionId(skuInfo.getSubUnionId());
                    jdOrders.setTraceType(skuInfo.getTraceType());
                    jdOrders.setSkuPayMonth(DateUtil.getStrTime(skuInfo.getPayMonth(),"yyyyMMdd"));
                    jdOrders.setSkuPopId(skuInfo.getPopId());
                    jdOrders.setSkuExt1(skuInfo.getExt1());
                    jdOrders.setCpActId(skuInfo.getCpActId());
                    jdOrders.setUnionRole(skuInfo.getUnionRole());
                    jdOrders.setGiftCouponKey(skuInfo.getGiftCouponKey());
                    jdOrders.setGiftCouponOcsAmount(Math.currencyFormatToF(skuInfo.getGiftCouponOcsAmount()));
                    jdOrders.setBizStatus(bizStatus);
                    jdOrders.setImgUrl(skuInfo.getGoodsInfo()!=null?skuInfo.getGoodsInfo().getImageUrl():null);
                    jdOrders.setModifyTime(DateUtil.getStrTime(skuInfo.getModifyTime()));
                    jdOrders.setBalanceExt(skuInfo.getBalanceExt());
                    jdOrders.setProPriceAmount(Math.currencyFormatToF(skuInfo.getProPriceAmount()));
                    jdOrders.setOwner(skuInfo.getGoodsInfo()!=null?skuInfo.getGoodsInfo().getOwner():null);
                    jdOrders.setMainSkuId(skuInfo.getGoodsInfo()!=null?skuInfo.getGoodsInfo().getMainSkuId():null);
                    jdOrders.setProductId(skuInfo.getGoodsInfo()!=null?skuInfo.getGoodsInfo().getProductId():null);
                    jdOrders.setShopName(skuInfo.getGoodsInfo()!=null?skuInfo.getGoodsInfo().getShopName():null);
                    jdOrders.setShopId(skuInfo.getGoodsInfo()!=null?skuInfo.getGoodsInfo().getShopId():null);
                    jdOrders.setCid1Name(skuInfo.getCategoryInfo()!=null?skuInfo.getCategoryInfo().getCid1Name():null);
                    jdOrders.setCid2Name(skuInfo.getCategoryInfo()!=null?skuInfo.getCategoryInfo().getCid2Name():null);
                    jdOrders.setCid3Name(skuInfo.getCategoryInfo()!=null?skuInfo.getCategoryInfo().getCid3Name():null);
                    jdOrders.setExpressStatus(skuInfo.getExpressStatus());
                    jdOrders.setFailReason(getPunishInfo(skuInfo.getValidCode()));
                    jdOrders.setRid(skuInfo.getRid() != null ? String.valueOf(skuInfo.getRid()) : null);
                    jdOrders.setItemId(skuInfo.getItemId());
                    jdOrders.setCallerItemId(skuInfo.getCallerItemId());
                    jdOrders.setUpdateTime(now);
                    jdOrdersMapper.update(jdOrders);
                }
            }
        }
    }

    public void ordersInfoAdd_byAppKey(OrderAgentResp[] orderAgentResps, OrderAgentReq orderAgentReq) {
        int now = DateUtil.getNowTime();
        if (orderAgentResps==null || orderAgentResps.length==0){
            logger.info("-----jd order is null.-------");
            return ;
        }
        for (OrderAgentResp skuInfo : orderAgentResps){
            try {

                //自定义参数不为空，且以cps_开头，这种订单为推老板订单，不入库
                String subUnionId = skuInfo.getSubUnionId();

                //是否开启自定义参数为空过滤（0-不过滤;1-过滤）
                String jd_order_sub_union_id = sysSettingMapper.getByKey("jd_order_sub_union_id");
                if(StringUtils.isNotBlank(jd_order_sub_union_id) && "1".equals(jd_order_sub_union_id)){
                    //速推订单的自定义参数为空
                    if(StringUtils.isBlank(subUnionId)){
                        continue;
                    }
                }

                if(StringUtils.isNotBlank(subUnionId) && subUnionId.startsWith("cps_")) {
                    continue;
                }

                if(skuInfo.getUnionId() != null && skuInfo.getUnionId().longValue() == 1002927559L){
                    //如果此订单下载到，则发钉钉报警提醒
                    if(skuInfo.getOrderId() != null && skuInfo.getOrderId().longValue() == 274719977598L){
                        String content = "订单库拉取京东订单监控提醒。\n订单号:274719977598";
                        ordersNotifyService.dingdingMsgAlarm(content);
                    }

                    //订单状态
                    int bizStatus = bizStatus(skuInfo.getValidCode());
                    // 添加京东订单
                    JdOrdersInfo newJdOrderInfo = new JdOrdersInfo();
                    newJdOrderInfo.setId(IdWorker.getId());
                    newJdOrderInfo.setFinishTime(DateUtil.getStrTime(skuInfo.getFinishTime()));
                    newJdOrderInfo.setOrderEmt(skuInfo.getOrderEmt());
                    newJdOrderInfo.setOrderId(skuInfo.getOrderId());
                    newJdOrderInfo.setDataId(skuInfo.getId());
                    newJdOrderInfo.setOrderIdOld(skuInfo.getOrderId());
                    newJdOrderInfo.setOrderTime(DateUtil.getStrTime(skuInfo.getOrderTime()));
                    newJdOrderInfo.setParentId(skuInfo.getParentId());
                    newJdOrderInfo.setPayMonth(skuInfo.getPayMonth());
                    newJdOrderInfo.setPlus(skuInfo.getPlus());
                    newJdOrderInfo.setPopId(skuInfo.getPopId());
                    newJdOrderInfo.setUnionId(skuInfo.getUnionId());
                    newJdOrderInfo.setExt1(skuInfo.getExt1());
                    newJdOrderInfo.setValidCode(skuInfo.getValidCode());
                    newJdOrderInfo.setActualCosPrice(Math.currencyFormatToF(skuInfo.getActualCosPrice()));
                    newJdOrderInfo.setActualFee(Math.currencyFormatToF(skuInfo.getActualFee()));
                    newJdOrderInfo.setCommissionRate(skuInfo.getCommissionRate());
                    newJdOrderInfo.setEstimateCosPrice(Math.currencyFormatToF(skuInfo.getEstimateCosPrice()));
                    newJdOrderInfo.setEstimateFee(Math.currencyFormatToF(skuInfo.getEstimateFee()));
                    newJdOrderInfo.setFinalRate(skuInfo.getFinalRate());
                    newJdOrderInfo.setCid1(skuInfo.getCid1());
                    newJdOrderInfo.setFrozenSkuNum(skuInfo.getSkuFrozenNum().intValue());
                    newJdOrderInfo.setPid(skuInfo.getPid());
                    newJdOrderInfo.setPositionId(skuInfo.getPositionId());
                    newJdOrderInfo.setPrice(Math.currencyFormatToF(skuInfo.getPrice()));
                    newJdOrderInfo.setCid2(skuInfo.getCid2());
                    newJdOrderInfo.setCid3(skuInfo.getCid3());
                    newJdOrderInfo.setSiteId(skuInfo.getSiteId());
                    newJdOrderInfo.setSkuId(skuInfo.getSkuId());
                    newJdOrderInfo.setSkuName(skuInfo.getSkuName());
                    newJdOrderInfo.setSkuNum(skuInfo.getSkuNum().intValue());
                    newJdOrderInfo.setSkuReturnNum(skuInfo.getSkuReturnNum().intValue());
                    newJdOrderInfo.setSubSideRate(skuInfo.getSubSideRate());
                    newJdOrderInfo.setSubsidyRate(skuInfo.getSubsidyRate());
                    newJdOrderInfo.setUnionAlias(skuInfo.getUnionAlias());
                    newJdOrderInfo.setUnionTag(skuInfo.getUnionTag());
                    //新版接口没有返回这个渠道组字段
                    //newJdOrderInfo.setUnionTrafficGroup(skuInfo.getUnionTrafficGroup());
                    newJdOrderInfo.setSkuValidCode(skuInfo.getValidCode());
                    newJdOrderInfo.setSubUnionId(skuInfo.getSubUnionId());
                    newJdOrderInfo.setTraceType(skuInfo.getTraceType());
                    newJdOrderInfo.setSkuPayMonth(DateUtil.getStrTime(skuInfo.getPayMonth(),"yyyyMMdd"));
                    newJdOrderInfo.setSkuPopId(skuInfo.getPopId());
                    newJdOrderInfo.setSkuExt1(skuInfo.getExt1());
                    newJdOrderInfo.setCpActId(skuInfo.getCpActId());
                    newJdOrderInfo.setUnionRole(skuInfo.getUnionRole());
                    newJdOrderInfo.setGiftCouponKey(skuInfo.getGiftCouponKey());
                    newJdOrderInfo.setGiftCouponOcsAmount(Math.currencyFormatToF(skuInfo.getGiftCouponOcsAmount()));
                    newJdOrderInfo.setBizStatus(bizStatus);
                    newJdOrderInfo.setImgUrl(skuInfo.getGoodsInfo()!=null?skuInfo.getGoodsInfo().getImageUrl():null);
                    newJdOrderInfo.setModifyTime(DateUtil.getStrTime(skuInfo.getModifyTime()));
                    newJdOrderInfo.setBalanceExt(skuInfo.getBalanceExt());
                    newJdOrderInfo.setProPriceAmount(Math.currencyFormatToF(skuInfo.getProPriceAmount()));
                    newJdOrderInfo.setOwner(skuInfo.getGoodsInfo()!=null?skuInfo.getGoodsInfo().getOwner():null);
                    newJdOrderInfo.setMainSkuId(skuInfo.getGoodsInfo()!=null?skuInfo.getGoodsInfo().getMainSkuId():null);
                    newJdOrderInfo.setProductId(skuInfo.getGoodsInfo()!=null?skuInfo.getGoodsInfo().getProductId():null);
                    newJdOrderInfo.setShopName(skuInfo.getGoodsInfo()!=null?skuInfo.getGoodsInfo().getShopName():null);
                    newJdOrderInfo.setShopId(skuInfo.getGoodsInfo()!=null?skuInfo.getGoodsInfo().getShopId():null);
                    newJdOrderInfo.setCid1Name(skuInfo.getCategoryInfo()!=null?skuInfo.getCategoryInfo().getCid1Name():null);
                    newJdOrderInfo.setCid2Name(skuInfo.getCategoryInfo()!=null?skuInfo.getCategoryInfo().getCid2Name():null);
                    newJdOrderInfo.setCid3Name(skuInfo.getCategoryInfo()!=null?skuInfo.getCategoryInfo().getCid3Name():null);
                    newJdOrderInfo.setExpressStatus(skuInfo.getExpressStatus());
                    newJdOrderInfo.setFailReason(getPunishInfo(skuInfo.getValidCode()));
                    newJdOrderInfo.setRid(skuInfo.getRid() != null ? String.valueOf(skuInfo.getRid()) : null);
                    newJdOrderInfo.setRequestpara(JSONObject.toJSONString(orderAgentReq));
                    newJdOrderInfo.setUpdateTime(now);
                    newJdOrderInfo.setCreateTime(now);
                    //保存订单
                    jdOrdersInfoMapper.add(newJdOrderInfo);
                }

            }catch (Exception e){
                logger.error("----ordersInfoAdd_byAppKey - err={}", e.getMessage());
            }
        }
    }


    @Override
    public void threadSyncJyOrder_byAppKey(List<JdOrderTimeVO> jdOrderTimeVOList){
        for (JdOrderTimeVO jdOrderTimeVO:jdOrderTimeVOList){
            syncTimeJyOrder_byAppKey(jdOrderTimeVO,1);
        }
    }

    public void syncTimeJyOrder_byAppKey(JdOrderTimeVO jdOrderTimeVO, int pageNo) {
        try {
            // 京佣计划
            JdCpsOrderResp jdCpsOrderResp = jdCpsOrderService.getCpsOrders_byAppKey(jdOrderTimeVO,pageNo);

            if (jdCpsOrderResp!=null){
                if (jdCpsOrderResp.getData()!=null &&
                        jdCpsOrderResp.getData().getResult()!=null && jdCpsOrderResp.getData().getResult().size()>0){
                    // 处理订单入库
                    jdCpsOrderService.orderAdd_byAppKey(jdCpsOrderResp.getData());
                    pageNo = pageNo+1;
                    syncTimeJyOrder_byAppKey(jdOrderTimeVO,pageNo);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("-----jy sync order err:--------",e);
        }
    }

    @Async("taskExecutor")
    @Override
    public void threadSyncJyOrder_byAppKey_consumer(JdOrderTimeVO jdOrderTimeVO, JdClient client, Integer downType) {
        syncTimeOrder_byAppKey(jdOrderTimeVO,1, client, downType);
    }


    public PageVO apiPull_byAppKey(JdOrderApiPullDto jdOrderApiPullDto) {
        JdOrderVO jdOrderVO = new JdOrderVO();
        List<JdOrders> list = new ArrayList<>();
        try {

            String jdSdkUrl = "http://api.jd.com/routerjson";
            JdClient client = new DefaultJdClient(jdSdkUrl,"", jdOrderApiPullDto.getAppkey(), jdOrderApiPullDto.getAppsecret());

            UnionOpenOrderAgentQueryRequest request = new UnionOpenOrderAgentQueryRequest();
            OrderAgentReq orderReq = new OrderAgentReq();
            orderReq.setPageIndex(jdOrderApiPullDto.getPageIndex());
            orderReq.setPageSize(jdOrderApiPullDto.getPageSize());

            SimpleDateFormat jdFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String startTime = jdFormat.format(new Date(jdOrderApiPullDto.getBeginTime()*1000L));
            String endTime = jdFormat.format(new Date(jdOrderApiPullDto.getEndTime()*1000L));
            orderReq.setStartTime(startTime);
            orderReq.setEndTime(endTime);
            orderReq.setType(jdOrderApiPullDto.getQueryType());

            orderReq.setFields("goodsInfo,categoryInfo"); //筛选出参，多项逗号分隔，目前支持：categoryInfo、goodsInfo
            request.setOrderReq(orderReq);
            UnionOpenOrderAgentQueryResponse response = client.execute(request);
            if(response != null ){
                OrderAgentQueryResult orderAgentQueryResult = response.getQueryResult();
                if(orderAgentQueryResult != null){
                    OrderAgentResp[] orderAgentResps =  orderAgentQueryResult.getData();
                    if(orderAgentResps != null || orderAgentResps.length > 0){
                        for (OrderAgentResp skuInfo : orderAgentResps) {

                            //自定义参数不为空，且以cps_开头，这种订单为推老板订单，不入库
                            String subUnionId = skuInfo.getSubUnionId();

                            //是否开启自定义参数为空过滤（0-不过滤;1-过滤）
                            String jd_order_sub_union_id = sysSettingMapper.getByKey("jd_order_sub_union_id");
                            if(StringUtils.isNotBlank(jd_order_sub_union_id) && "1".equals(jd_order_sub_union_id)){
                                //速推订单的自定义参数为空
                                if(StringUtils.isBlank(subUnionId)){
                                    continue;
                                }
                            }

                            if(StringUtils.isNotBlank(subUnionId) && subUnionId.startsWith("cps_")) {
                                logger.info("----JD cps orders : id={}, skuid: {}, orderid: {}, validCode={}, price={}, skuFrozenNum={}, skuReturnNum={}, actualFee={}, subUnionId={}",
                                        new Object[]{skuInfo.getId(), skuInfo.getSkuId(), skuInfo.getOrderId(), skuInfo.getValidCode(), skuInfo.getPrice(), skuInfo.getSkuFrozenNum(), skuInfo.getSkuReturnNum(), skuInfo.getActualFee(),subUnionId});
                                continue;
                            }

                            logger.info("----JD orders : id={}, skuid: {}, orderid: {}, validCode={}, price={}, skuFrozenNum={}, skuReturnNum={}, actualFee={}",
                                    new Object[]{skuInfo.getId(), skuInfo.getSkuId(), skuInfo.getOrderId(), skuInfo.getValidCode(), skuInfo.getPrice(), skuInfo.getSkuFrozenNum(), skuInfo.getSkuReturnNum(), skuInfo.getActualFee()});

                            if(skuInfo.getPrice() == null || skuInfo.getPrice().doubleValue() <= 0){
                                //价格等于0，不处理
                                continue;
                            }

                            //update by:20221123 待付款不处理  validCode = 15 待付款
                            if(skuInfo.getValidCode() != null  && skuInfo.getValidCode().intValue() == 15){
                                //validCode = 15 待付款，不处理
                                continue;
                            }

                            //订单状态
                            int bizStatus = bizStatus(skuInfo.getValidCode());

                            // 添加京东订单
                            JdOrders newJdOrder = new JdOrders();
                            newJdOrder.setId(IdWorker.getId());
                            newJdOrder.setFinishTime(DateUtil.getStrTime(skuInfo.getFinishTime()));
                            newJdOrder.setOrderEmt(skuInfo.getOrderEmt());
                            newJdOrder.setOrderId(skuInfo.getOrderId());
                            newJdOrder.setDataId(skuInfo.getId());
                            newJdOrder.setOrderIdOld(skuInfo.getOrderId());
                            newJdOrder.setOrderTime(DateUtil.getStrTime(skuInfo.getOrderTime()));
                            newJdOrder.setParentId(skuInfo.getParentId());
                            newJdOrder.setPayMonth(skuInfo.getPayMonth());
                            newJdOrder.setPlus(skuInfo.getPlus());
                            newJdOrder.setPopId(skuInfo.getPopId());
                            newJdOrder.setUnionId(skuInfo.getUnionId());
                            newJdOrder.setExt1(skuInfo.getExt1());
                            newJdOrder.setValidCode(skuInfo.getValidCode());
                            newJdOrder.setActualCosPrice(Math.currencyFormatToF(skuInfo.getActualCosPrice()));
                            newJdOrder.setActualFee(Math.currencyFormatToF(skuInfo.getActualFee()));
                            newJdOrder.setCommissionRate(skuInfo.getCommissionRate());
                            newJdOrder.setEstimateCosPrice(Math.currencyFormatToF(skuInfo.getEstimateCosPrice()));
                            newJdOrder.setEstimateFee(Math.currencyFormatToF(skuInfo.getEstimateFee()));
                            newJdOrder.setFinalRate(skuInfo.getFinalRate());
                            newJdOrder.setCid1(skuInfo.getCid1());
                            newJdOrder.setFrozenSkuNum(skuInfo.getSkuFrozenNum().intValue());
                            newJdOrder.setPid(skuInfo.getPid());
                            newJdOrder.setPositionId(skuInfo.getPositionId());
                            newJdOrder.setPrice(Math.currencyFormatToF(skuInfo.getPrice()));
                            newJdOrder.setCid2(skuInfo.getCid2());
                            newJdOrder.setCid3(skuInfo.getCid3());
                            newJdOrder.setSiteId(skuInfo.getSiteId());
                            newJdOrder.setSkuId(skuInfo.getSkuId());
                            newJdOrder.setSkuName(skuInfo.getSkuName());
                            newJdOrder.setSkuNum(skuInfo.getSkuNum().intValue());
                            newJdOrder.setSkuReturnNum(skuInfo.getSkuReturnNum().intValue());
                            newJdOrder.setSubSideRate(skuInfo.getSubSideRate());
                            newJdOrder.setSubsidyRate(skuInfo.getSubsidyRate());
                            newJdOrder.setUnionAlias(skuInfo.getUnionAlias());
                            newJdOrder.setUnionTag(skuInfo.getUnionTag());
                            //新版接口没有返回这个渠道组字段
                            //newJdOrder.setUnionTrafficGroup(skuInfo.getUnionTrafficGroup());
                            newJdOrder.setSkuValidCode(skuInfo.getValidCode());
                            newJdOrder.setSubUnionId(skuInfo.getSubUnionId());
                            newJdOrder.setTraceType(skuInfo.getTraceType());
                            newJdOrder.setSkuPayMonth(DateUtil.getStrTime(skuInfo.getPayMonth(), "yyyyMMdd"));
                            newJdOrder.setSkuPopId(skuInfo.getPopId());
                            newJdOrder.setSkuExt1(skuInfo.getExt1());
                            newJdOrder.setCpActId(skuInfo.getCpActId());
                            newJdOrder.setUnionRole(skuInfo.getUnionRole());
                            newJdOrder.setGiftCouponKey(skuInfo.getGiftCouponKey());
                            newJdOrder.setGiftCouponOcsAmount(Math.currencyFormatToF(skuInfo.getGiftCouponOcsAmount()));
                            newJdOrder.setBizStatus(bizStatus);
                            newJdOrder.setImgUrl(skuInfo.getGoodsInfo() != null ? skuInfo.getGoodsInfo().getImageUrl() : null);
                            newJdOrder.setModifyTime(DateUtil.getStrTime(skuInfo.getModifyTime()));
                            newJdOrder.setBalanceExt(skuInfo.getBalanceExt());
                            newJdOrder.setProPriceAmount(Math.currencyFormatToF(skuInfo.getProPriceAmount()));
                            newJdOrder.setOwner(skuInfo.getGoodsInfo() != null ? skuInfo.getGoodsInfo().getOwner() : null);
                            newJdOrder.setMainSkuId(skuInfo.getGoodsInfo() != null ? skuInfo.getGoodsInfo().getMainSkuId() : null);
                            newJdOrder.setProductId(skuInfo.getGoodsInfo() != null ? skuInfo.getGoodsInfo().getProductId() : null);
                            newJdOrder.setShopName(skuInfo.getGoodsInfo() != null ? skuInfo.getGoodsInfo().getShopName() : null);
                            newJdOrder.setShopId(skuInfo.getGoodsInfo() != null ? skuInfo.getGoodsInfo().getShopId() : null);
                            newJdOrder.setCid1Name(skuInfo.getCategoryInfo() != null ? skuInfo.getCategoryInfo().getCid1Name() : null);
                            newJdOrder.setCid2Name(skuInfo.getCategoryInfo() != null ? skuInfo.getCategoryInfo().getCid2Name() : null);
                            newJdOrder.setCid3Name(skuInfo.getCategoryInfo() != null ? skuInfo.getCategoryInfo().getCid3Name() : null);
                            newJdOrder.setExpressStatus(skuInfo.getExpressStatus());
                            newJdOrder.setFailReason(getPunishInfo(skuInfo.getValidCode()));
                            newJdOrder.setRid(skuInfo.getRid() != null ? String.valueOf(skuInfo.getRid()) : null);
                            newJdOrder.setItemId(skuInfo.getItemId());
                            newJdOrder.setCallerItemId(skuInfo.getCallerItemId());

                            int now = DateUtil.getNowTime();

                            newJdOrder.setUpdateTime(now);
                            newJdOrder.setCreateTime(now);

                            list.add(newJdOrder);
                        }
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            logger.error("-----jdorder apiPull_byAppKey order err:--------",e);
        } finally {
            jdOrderVO.setRecords(list);
            return jdOrderVO;
        }
    }

}
